package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import entity.UserInfo;
import util.DBAccess;

public class UserDao {

	//注册功能
	public void add(UserInfo user) {
		String sql = "insert into userinfo values(null,?,?,0)";
		try (Connection conn = new DBAccess().getConnection(); PreparedStatement ps = conn.prepareStatement(sql);) {
			
			ps.setString(1, user.getUserName());
			ps.setString(2, user.getPwd());
			ps.execute();

			ps.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void updateAdmin(String userName){
		String sql = "update userinfo set isAdmin = 1 where uname = ?";
		try (Connection conn = new DBAccess().getConnection(); PreparedStatement ps = conn.prepareStatement(sql);) {
			
			ps.setString(1, userName);
			ps.execute();
			ps.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}


	public UserInfo search(int userId) {
		UserInfo user = new UserInfo();
		String sql = "select * from userinfo where id = ?";
		try (Connection conn = new DBAccess().getConnection(); PreparedStatement ps = conn.prepareStatement(sql);) {
			ps.setInt(1, userId);
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				user.setUserId(userId);
				user.setUserName(rs.getString(2));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return user;
	}
	
	public UserInfo search(String userName) {
		UserInfo user = new UserInfo();
		String sql = "select * from userinfo where uname = ?";
		try (Connection conn = new DBAccess().getConnection(); PreparedStatement ps = conn.prepareStatement(sql);) {
			ps.setString(1, userName);
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				user.setUserId(rs.getInt(1));
				user.setUserName(userName);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return user;
	}
	
	
	
}
